package com.dbflow5;

import com.dbflow5.config.FlowConfig;
import com.dbflow5.config.FlowLog;
import com.dbflow5.config.FlowManager;
import com.dbflow5.database.OhosSQLiteOpenHelper;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

import java.util.function.Function;

public class DBFlowInstrumentedTestRule implements TestRule {
    private final Function<FlowConfig.Builder, Void> dbConfigBlock;

    public DBFlowInstrumentedTestRule(Function<FlowConfig.Builder, Void> dbConfigBlock) {
        this.dbConfigBlock = dbConfigBlock;
    }

    @Override
    public Statement apply(Statement base, Description description) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                FlowLog.setMinimumLoggingLevel(FlowLog.Level.V);
                FlowManager.init(DemoApp.context, builder -> {
                    builder.database(TestDatabase.class, builder1 -> {
                        builder1.transactionManagerCreator(ImmediateTransactionManager::new);
                        return null;
                    },  OhosSQLiteOpenHelper.createHelperCreator(DemoApp.context));
                    dbConfigBlock.apply(builder);
                    return null;
                });

                try {
                    base.evaluate();
                } finally {
                    FlowManager.destroy();
                }
            }
        };
    }

    public static DBFlowInstrumentedTestRule create(Function<FlowConfig.Builder, Void> fn) {
       return new DBFlowInstrumentedTestRule(fn);
    }
}
